<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="上课时间" prop="createTime">
        <el-date-picker
          :clearable="false"
          v-model="queryParams.createTime"
          type="date"
          format="yyyy-MM-dd"
          value-format="yyyy-MM-dd HH:mm:ss"
          placeholder="请选择上课时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="学生姓名" prop="name">
        <el-input
          v-model="queryParams.studentName"
          placeholder="请输入学生姓名"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="所属班级" prop="classId">
        <el-select v-model="queryParams.classId" clearable placeholder="请选择所属班级">
          <el-option
            v-for="dict in this.classOptions"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <el-table v-loading="loading" :data="recordList" :row-style="getRowStyle" @selection-change="handleSelectionChange">
      <el-table-column label="学生姓名" align="center" prop="studentName" fixed />
      <el-table-column label="课程名称" align="center" prop="courseName" />
      <el-table-column label="所属班级" align="center" prop="className" />
      <el-table-column label="上课时间" align="center" prop="sort">
        <template slot-scope="scope">
          <span>{{ defaultData[scope.row.sort - 1].time }}</span>
        </template>
      </el-table-column>
      <el-table-column label="打卡时间" align="center" prop="createTime">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}:{s} ') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="评分" align="center" prop="score">
        <template slot-scope="scope">
          <el-rate v-if="scope.row.score"
            style="margin-top: 10px"
            v-model="scope.row.score" disabled
            :colors="['#99A9BF', '#F7BA2A', '#FF9900']">
          </el-rate>
          <el-tag v-else type="info">未评分</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="教学成果" align="center" prop="filePathList">
        <template slot-scope="scope">
          <span v-for="path in scope.row.filePathList">
            <img v-if="!path.includes('mp4')"  width="25%" :src="path" alt="" @click="()=>{dialogVisible=true;dialogImageUrl = path}">
            <el-link v-else type="primary" @click="playVideo(path)">查看视频</el-link>
          </span>
          <el-tag v-if="!scope.row.filePathList" type="info">暂未上传</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="教师反馈" prop="comment" show-overflow-tooltip>
        <template slot-scope="scope">
          <span v-if="scope.row.comment">{{scope.row.comment}}</span>
          <el-tag v-if="!scope.row.comment" type="info">暂无反馈</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            :disabled="scope.row.score"
            @click="handleUpdate(scope.row)"
            v-has-role="['ysg:work']"
          >课后评价</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改学生管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" center append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px" size="large">
        <el-form-item label="学生表现" prop="score">
          <el-rate
            style="margin-top: 10px"
            v-model="form.score"
            :colors="['#99A9BF', '#F7BA2A', '#FF9900']">
          </el-rate>
        </el-form-item>
        <el-form-item label="教学成果" prop="filePaths">
          <el-upload
            v-if="!uploadVideo"
            ref="upload"
            list-type="picture-card"
            accept=".jpg, .png,"
            :action="upload.url"
            :headers="upload.headers"
            :file-list="upload.fileList"
            :on-progress="handleFileUploadProgress"
            :on-success="handleFileSuccess"
            :on-change="handleFileChange"
            :auto-upload="false">
            <i class="el-icon-plus"></i>
          </el-upload>
          <el-upload
            v-else
            ref="upload"
            drag
            accept=" .mp4"
            :action="upload.url"
            :headers="upload.headers"
            :file-list="upload.fileList"
            :on-progress="handleFileUploadProgress"
            :on-success="handleFileSuccess"
            :on-change="handleFileChange"
            :auto-upload="false">
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
          </el-upload>
          <el-link type="primary" @click="()=>{uploadVideo = !uploadVideo}">{{uploadVideo ? '我要上传图片？':'我要上传视频？'}}</el-link>
        </el-form-item>
        <el-form-item label="教师反馈" prop="comment">
          <el-input
            type="textarea"
            :rows="10"
            placeholder="请输入内容"
            v-model="form.comment">
          </el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <el-dialog :visible.sync="dialogVisible">
      <img width="100%" :src="dialogImageUrl" alt="">
    </el-dialog>
    <el-dialog :visible.sync="playerVisible" fullscreen>
      <video-player :video-url="videoUrl"></video-player>
    </el-dialog>
  </div>
</template>

<script>
import { listStudent, getStudent, delStudent, addStudent, updateStudent } from "@/api/ysg/student"
import {getSignInRecords,rate} from '@/api/ysg/work'
import {getClassOptions} from "@/api/ysg/common"
import VideoPlayer from "./videoPlayer.vue";
import moment from "moment";
import { getToken } from "@/utils/auth";
import {getVideoCover} from "@/utils/video"
export default {
  name: "Student",
  dicts: ['effective'],
  components:{ VideoPlayer},
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 表格数据
      recordList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        studentName: null,
        classId: null,
        createTime:null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        score: [
          { required: true, message: "评分不能为空", trigger: "blur" }
        ],
      },
      classOptions:[],
      defaultData :[
        {
          time: '09:00-10:30',
        },
        {
          time: '10:30-12:00',
        },
        {
          time: '13:30-15:00',

        },
        {
          time: '15:00-16:30',

        },
        {
          time: '16:30-18:00',

        },
        {
          time: '18:00-19:30',
        }
      ],
      uploadVideo:false,
      // 上传参数
      upload: {
        // 是否禁用上传
        isUploading: false,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/common/upload",
        // 上传的文件列表
        fileList: []
      },
      dialogVisible:false,
      dialogImageUrl:'',
      playerVisible:false,
      videoUrl:'',
    }
  },
  created() {
    this.getList()
    this.getClassOptions()
  },
  methods: {
    getClassOptions(keyWord) {
      getClassOptions(keyWord).then(res=>{
        this.classOptions = res.data
      })
    },
    /** 查询列表 */
    getList() {
      this.loading = true
      getSignInRecords(this.queryParams).then(response => {
        this.recordList = response.rows
        this.recordList.forEach(item=>{
          if(item.filePaths) {
            item.filePathList = JSON.parse(item.filePaths)
          }
        })
        this.loading = false
        this.total = response.total
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        score:null,
        filePathList:[],
        comment:null,
      }
      this.resetForm("form")
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm")
      this.queryParams = {}
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = "添加学生管理"
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      this.form.id = row.id
      this.form.studentId = row.studentId
      this.form.studentName = row.studentName
      this.open = true
      this.title = "课后评价"
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if(this.form.filePathList) {
            this.form.filePaths = JSON.stringify(this.form.filePathList)
          }
           rate(this.form).then(res=> {
             this.$modal.msgSuccess("保存成功")
             this.open = false
             this.getList()
           })
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$modal.confirm('是否确认删除学生管理编号为"' + ids + '"的数据项？').then(function() {
        return delStudent(ids)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => {})
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('ysg/student/export', {
        ...this.queryParams
      }, `student_${new Date().getTime()}.xlsx`)
    },
    // 文件提交处理
    submitUpload() {
      this.$refs.upload.submit();
    },
// 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
// 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.isUploading = false;
      this.form.filePathList.push(response.url);
      this.$modal.msgSuccess(response.msg)
    },
    handleFileChange(file,fileList) {
      console.log(file);
      console.log(fileList);
      if(file.name.includes(".mp4")) {
        getVideoCover(file.raw).then(res=>{
          fileList.forEach(item=>{
            if(item.name === file.name) {
              const coverFile = new File([res], `${file.name}_cover.jpg`, { type: 'image/jpeg' });
              item.coverUrl = URL.createObjectURL(res);
              item.coverFile = coverFile;
            }
          })
        })
      }
      this.submitUpload()
    },
    getRowStyle() {
      return {height: '100px'}
    },
    // 从视频 URL 生成封面图
    generateCoverFromUrl(videoUrl, rowId) {
      const video = document.createElement("video");
      video.src = videoUrl;
      video.crossOrigin = "anonymous"; // 解决跨域（本地服务器需配置 CORS）
      video.preload = "metadata"; // 仅加载元数据，提升性能

      // 监听第一帧加载完成
      video.addEventListener("loadeddata", () => {
        // 生成封面图
        const canvas = document.createElement("canvas");
        canvas.width = 200; // 封面图宽度（适配表格列）
        canvas.height = 120; // 封面图高度（保持 16:9 比例）
        const ctx = canvas.getContext("2d");
        ctx.drawImage(video, 0, 0, canvas.width, canvas.height);

        // 转为图片 URL
        const coverUrl = canvas.toDataURL("image/jpeg");
        // 获取视频时长并格式化
        const duration = this.formatDuration(video.duration);

        // 更新表格数据
        const row = this.tableData.find(item => item.id === rowId);
        if (row) {
          row.coverUrl = coverUrl;
          row.duration = duration;
        }

        // 释放资源
        video.remove();
      });

      // 处理视频加载失败（URL 错误等）
      video.addEventListener("error", () => {
        console.error(`视频加载失败：${videoUrl}，请检查 URL 是否正确`);
      });
    },
    // 播放视频（弹窗播放）
    playVideo(videoUrl) {
      this.videoUrl = videoUrl
      this.playerVisible = true
    }
  }
}
</script>
<style scoped>
</style>
